// pages/home-music/index.js
import {userStore,playerStore} from '../../store/index'
import queryRect from '../../utils/query-rect'
const db = wx.cloud.database()
Page({

  data: {
    swiperHeight: 0,
    banners:[],
    recommendSongs:[],
    hotSongs:[],
    similarSongs:[],
    hotSongMenu:[],
    recommendSongMenu:[],
    currentSong:{},
    isPlaying: false,
    playAnimState: "paused",
    reloadAnimState: "paused",
    hotReloadAnimState: "paused",
    haveCollection:false,
    canRecommend:false,
    collectionSong:"",
    recommendSong:"",
    isLogin:"false",
    username:"",
    tab:0
  },

  onLoad: function (options) {
      //获取页面数据
      this.getPageData()
      //从store中获取共享数据
      this.setupPlayerStoreListener()
  },

  //======================点击搜索===========================
  handleSearchClick:function (){
    wx.navigateTo({
      url: '/pages/detail-search/index',
    })
  },

//========================获取图片的高度======================
  handleSwiperImageLoaded:function(){
    
    queryRect(".swiper-image").then(res=>{
      var rect = res[0]
      this.setData({ swiperHeight:rect.height })
    })
    
  },

  //=========================网络请求=========================
  getPageData:function(){
    //获取banner
    var that = this
    db.collection('banners').get({
      success:function(res){
        that.setData({
          banners:res.data
        })
      }
    })

    //获取排行榜
    db.collection('recommendSongs').get({
      success:function(res){
        that.setData({
          recommendSongs:res.data
        })
      }
    })

    //获取热门歌单
    db.collection('songs')
    .aggregate()
    .sample({
      size:3
    })
    .end()
    .then(res=>{
      this.setData({hotSongs:res.list})
    })
    //获取推荐歌单
    db.collection('recommendSongMenu').get({
      success:function(res){
        that.setData({
          recommendSongMenu:res.data
        })
      }
    })

  },

  //=========================获取store中的共享数据==============
  setupPlayerStoreListener:function(){
    //播放器的监听
    playerStore.onStates(["currentSong","isPlaying"],({currentSong ,isPlaying})=>{
      if(currentSong) this.setData({currentSong})
      if(isPlaying !== undefined) this.setData({ 
        isPlaying ,
        playAnimState: isPlaying ? "running":"paused"
      })
    })
    
  },

  //=========================点击歌曲===========================
  handleSongItemClick:function(event){
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs",this.data.recommendSongs)
    playerStore.setState("playListIndex", index)
  },

  //=========================点击播放热门歌曲=====================
  handleHotSongItemClick:function(event){
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs",this.data.hotSongs)
    playerStore.setState("playListIndex", index)
  },

  //=========================点击相似歌曲====================
  handleSimilarItemClick:function(event){
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs",this.data.similarSongs)
    playerStore.setState("playListIndex", index)
  },

  //=========================刷新热门歌曲======================
  handleReloadHotSongClick:function(){
    this.setData({hotReloadAnimState:"running"})
    db.collection('songs')
    .aggregate()
    .sample({
      size:3
    })
    .end()
    .then(res=>{
      this.setData({hotSongs:res.list})
    })
    this.sleep(1000)
    this.setData({hotReloadAnimState:"paused"})
  },

  //========================刷新推荐歌曲======================
  handleReloadSimilarClick:function(){
    this.setData({reloadAnimState:"running"})
    this.getSimilarSongs()
    this.sleep(1000)
    this.setData({reloadAnimState:"paused"})
    
  },

  sleep:function(milliSeconds) {
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + milliSeconds) {
    }//暂停一段时间 10000=1S。
},

  //==========================点击小播放器=========================
  handlePlayBtnClick:function(event){
    playerStore.dispatch("changeMusicPlayStatusAction",!this.data.isPlaying)
    
  },

  handlePlayBarClick:function(){
    wx.navigateTo({
      url: '/pages/music-player/index?id=' + this.data.currentSong.id,
    })
  },

  getSimilarSongs:async function(){
    userStore.onState("isLogin",(value)=>{
      this.setData({
        isLogin:value
      })
    })
    userStore.onState("username",(value)=>{
      this.setData({username:value})
    })

    if(this.data.isLogin == "true"){
     await db.collection('collectionMenu')
      .where({
        userName:this.data.username
      })
      .get()
      .then(res=>{
        var length = res.data.length
        var randomArray = []
        for(var i = 0 ;i < length; i++){
          var data = res.data[i].collectionList.songInfo
          randomArray = randomArray.concat(data)
        }
       
        var length = randomArray.length
        var random = parseInt(Math.random() * length)
        const id = randomArray[random].id
        this.setData({similarId:id})
        
      })

      //推荐
      await db.collection('songs')
      .where({
        id:this.data.similarId
      })
      .get()
      .then(res=>{
        console.log(res.data[0].tab);
        this.setData({
          tab:res.data[0].tab,
          recommendSong:res.data[0].name
        })
      })
      await db.collection('songs')
      .where({
        tab:this.data.tab
      }) 
      .limit(10)
      .get()
      .then(res=>{
        
          var arr = res.data

          //随机
       
          for(var i = arr.length-1;i>=0;i--){
            var randomIndex = Math.floor(Math.random()*(i+1))
            var itemAtIndex = arr[randomIndex];
            arr[randomIndex] = arr[i];
            arr[i] === itemAtIndex;       
          }
          //去重
         let obj = {}
         arr = arr.reduce((newArr , next)=>{
           obj[next.id] ? "" : (obj[next.id] = true && newArr.push(next))
           return newArr
         },[])
     
          //去掉原歌曲
          var element = this.data.similarId
          var new_arr = []
          arr.forEach(item =>(item.id != element && new_arr.push(item) ))
          
  
          while(new_arr.length > 3){
            new_arr.pop()
            // console.log('1');
          }
              
          if(new_arr.length == 3){
            this.setData({similarSongs:new_arr})
            this.setData({
              collectionSong:this.data.recommendSong,
              haveCollection:true,
              canRecommend:true
            })
          }else{
             db.collection('similarMenu').where({
              id:this.data.similarId 
            })
            .get()
            .then( res =>{
              console.log(res.data[0].collectionList.songInfo);
                this.setData({similarSongs:res.data[0].collectionList.songInfo})
                this.setData({
                  collectionSong:res.data[0].name,
                  haveCollection:true,
                  canRecommend:false
                })
              
              console.log(res.data.collectionList.songInfo);
              
            })
            .catch(err=> {
              // console.log('没有值');
            })
          }
      })

      

    }
  },

  onReachBottom:function(){
    this.getSimilarSongs()
  }

})